import request from '@/utils/request';
import { API } from '@/utils/config';

// 订单状态枚举
export enum OrderStatus {
  Pending = '1',    // 待付款
  Paid = '2',       // 待发货
  Partial = '3',    // 部分发货
  Shipped = '4',    // 待收货
  Completed = '5',  // 交易完成
  Closed = '6'      // 交易关闭
}

// 售后状态枚举
export enum AfterSaleStatus {
  None = '0',       // 无售后
  Processing = '1', // 售后中
  WaitingMerchant = '2', // 待商家处理
  Closed = '3',     // 售后关闭
  Refunded = '4'    // 退款成功
}

// 订单项类型
export interface OrderItem {
  id: string;
  productId: string;
  skuId: string;
  name: string;
  image: string;
  price: string;
  quantity: number;
  specs: string;
  discount: number;
  shipping: number;
  shippedCount?: number;
  afterSaleStatus?: string;
}

// 订单类型
export interface Order {
  id: string;
  orderNo: string;
  orderTime: string;
  userId: string;
  customerName: string;
  orderStatus: string | OrderStatus;
  afterSaleStatus: string | AfterSaleStatus;
  receivableAmount: string;
  shippedCount: number;
  totalCount: number;
  isOverdue: boolean;
  items: OrderItem[];
  channel: string; // 推广渠道
  userNote: string; // 用户备注
  orderNote: string; // 订单备注
  receiverName: string; // 收货人
  receiverPhone: string; // 联系电话
  receiverAddress: string; // 收货地址
  receiverRegion: string; // 收货区域
}

// 订单列表查询参数
export interface OrderListParams {
  page: number;
  pageSize: number;
  searchType?: string;
  keyword?: string;
  startDate?: string;
  endDate?: string;
  status?: string;
  refundStatus?: string;
  channel?: string;
}

// 订单列表响应
export interface OrderListResponse {
  list: Order[];
  total: number;
}

/**
 * 獲取訂單列表
 * @param params 查詢參數
 */
export function getOrderList(params: OrderListParams) {
  return request({
    url: `${API.CLASSES}/Order`,
    method: 'get',
    params: {
      limit: params.pageSize,
      skip: (params.page - 1) * params.pageSize,
      where: JSON.stringify(buildOrderQuery(params))
    }
  });
}

// 构建订单查询条件
function buildOrderQuery(params: OrderListParams) {
  const query: any = {};
  
  // 按关键词搜索
  if (params.keyword) {
    if (params.searchType === 'orderNo') {
      // 訂單編號使用精確匹配
      const keyword = params.keyword.trim();
      
      // 如果是完整的objectId格式（24位十六進制），則使用精確匹配
      if (/^[0-9a-fA-F]{24}$/.test(keyword)) {
        query.objectId = keyword;
      } else {
        // 否則，匹配訂單號
        query.orderNo = keyword;
      }
    } else if (params.searchType === 'productName') {
      query.items = { $elemMatch: { productName: { $regex: params.keyword } } };
    } else if (params.searchType === 'receiverName') {
      query.receiverName = { $regex: params.keyword };
    } else if (params.searchType === 'receiverPhone') {
      query.receiverPhone = { $regex: params.keyword };
    }
  }
  
  // 按时间范围查询
  if (params.startDate && params.endDate) {
    query.createdAt = {
      $gte: { "__type": "Date", "iso": `${params.startDate}T00:00:00.000Z` },
      $lte: { "__type": "Date", "iso": `${params.endDate}T23:59:59.999Z` }
    };
  }
  
  // 按状态查询
  if (params.status) {
    query.status = parseInt(params.status, 10);
  }
  
  // 按售后状态查询
  if (params.refundStatus) {
    query.refundStatus = parseInt(params.refundStatus, 10);
  }
  
  // 按渠道查询
  if (params.channel) {
    query.channel = params.channel;
  }
  
  return query;
}

/**
 * 獲取訂單詳情
 * @param id 訂單ID
 */
export function getOrderDetail(id: string) {
  return request({
    url: `${API.CLASSES}/Order/${id}`,
    method: 'get'
  });
}

/**
 * 更新訂單狀態
 * @param id 訂單ID
 * @param status 狀態
 */
export function updateOrderStatus(id: string, status: OrderStatus) {
  return request({
    url: `${API.CLASSES}/Order/${id}`,
    method: 'put',
    data: { status: parseInt(status, 10) }
  });
}

/**
 * 取消訂單
 * @param id 訂單ID
 * @param reason 取消原因
 */
export function cancelOrder(id: string, reason: string) {
  return request({
    url: `${API.CLASSES}/Order/${id}`,
    method: 'put',
    data: { 
      status: parseInt(OrderStatus.Closed, 10),
      cancelReason: reason,
      updatedAt: { "__type": "Date", "iso": new Date().toISOString() }
    }
  });
}

/**
 * 修改收貨地址
 * @param id 訂單ID
 * @param addressData 地址數據
 */
export function updateOrderAddress(id: string, addressData: {
  receiverName: string;
  receiverPhone: string;
  receiverRegion: string;
  receiverAddress: string;
}) {
  return request({
    url: `${API.CLASSES}/Order/${id}`,
    method: 'put',
    data: addressData
  });
}

/**
 * 刪除訂單
 * @param id 訂單ID
 */
export function deleteOrder(id: string) {
  return request({
    url: `${API.CLASSES}/Order/${id}`,
    method: 'delete'
  });
}

/**
 * 修改訂單價格
 * @param id 訂單ID
 * @param amount 新價格
 */
export function changeOrderPrice(id: string, amount: number) {
  return request({
    url: `${API.CLASSES}/Order/${id}`,
    method: 'put',
    data: { payAmount: amount }
  });
}

/**
 * 訂單發貨
 * @param id 訂單ID
 * @param trackingNumber 物流單號
 * @param expressCompany 物流公司
 */
export function shipOrder(id: string, trackingNumber: string, expressCompany: string) {
  return request({
    url: `${API.CLASSES}/Order/${id}`,
    method: 'put',
    data: { 
      trackingNumber, 
      expressCompany,
      status: parseInt(OrderStatus.Shipped, 10),
      updatedAt: { "__type": "Date", "iso": new Date().toISOString() }
    }
  });
}

/**
 * 添加訂單備注
 * @param id 訂單ID
 * @param note 備注內容
 */
export function addOrderNote(id: string, note: string) {
  return request({
    url: `${API.CLASSES}/Order/${id}`,
    method: 'put',
    data: { 
      orderNote: note,
      updatedAt: { "__type": "Date", "iso": new Date().toISOString() }
    }
  });
}

/**
 * 批量創建訂單
 * @param orders 訂單數據列表
 */
export function batchCreateOrders(orders: any[]) {
  return request({
    url: `${API.BATCH}`,
    method: 'post',
    data: {
      requests: orders.map(order => {
        // 處理訂單資料格式為LeanCloud需要的結構
        // 移除不符合數據庫結構的字段
        const { id, selected, priceAndQuantity, ...orderData } = order;
        
        // 保存 objectId 如果存在
        const objectId = orderData.objectId;
        
        // 處理訂單狀態為數字型態
        let statusNumber = 1;
        if (typeof orderData.orderStatus === 'string') {
          switch (orderData.orderStatus) {
            case 'pending': statusNumber = 1; break;
            case 'paid': statusNumber = 2; break;
            case 'partial': statusNumber = 3; break;
            case 'shipped': statusNumber = 4; break;
            case 'completed': statusNumber = 5; break;
            case 'closed': statusNumber = 6; break;
            default: statusNumber = parseInt(orderData.orderStatus, 10) || 1;
          }
        } else {
          statusNumber = orderData.orderStatus || 1;
        }
        
        // 處理售後狀態為數字型態
        let afterSaleStatusNumber = 0;
        if (typeof orderData.afterSaleStatus === 'string') {
          if (orderData.afterSaleStatus === '无售后') {
            afterSaleStatusNumber = 0;
          } else {
            afterSaleStatusNumber = parseInt(orderData.afterSaleStatus, 10) || 0;
          }
        } else {
          afterSaleStatusNumber = orderData.afterSaleStatus || 0;
        }
        
        // 處理金額為數字
        let amount = 0;
        if (orderData.totalAmount) {
          // 如果有 totalAmount 直接使用
          amount = typeof orderData.totalAmount === 'number' ? 
            orderData.totalAmount : 
            parseFloat(orderData.totalAmount);
        } else if (orderData.payAmount) {
          // 如果有 payAmount 使用
          amount = typeof orderData.payAmount === 'number' ? 
            orderData.payAmount : 
            parseFloat(orderData.payAmount);
        } else if (orderData.receivableAmount) {
          // 如果有 receivableAmount 且是字符串，則嘗試轉換
          amount = typeof orderData.receivableAmount === 'string' ? 
            parseFloat(orderData.receivableAmount.replace(/[^\d.]/g, '')) : 
            (typeof orderData.receivableAmount === 'number' ? orderData.receivableAmount : 0);
        } else if (orderData.items && Array.isArray(orderData.items)) {
          // 如果都沒有，則從商品項計算
          amount = orderData.items.reduce((total: number, item: any) => {
            const itemPrice = typeof item.price === 'number' ? 
              item.price : 
              (typeof item.price === 'string' ? parseFloat(item.price.replace(/[^\d.]/g, '')) : 0);
            return total + (itemPrice * (item.quantity || 1));
          }, 0);
        }
        
        // 處理時間
        const orderTimeDate = orderData.orderTime ? 
          { "__type": "Date", "iso": new Date(orderData.orderTime).toISOString() } :
          { "__type": "Date", "iso": new Date().toISOString() };
        
        // 構建符合LeanCloud的訂單資料
        const leanCloudOrderData: any = {
          orderNo: orderData.orderNo || order.id,
          totalAmount: amount,
          payAmount: amount,
          discountAmount: 0,
          status: statusNumber,
          payStatus: statusNumber > 1 ? 1 : 0, // 已付款或未付款
          payType: 1, // 假設都是微信支付
          shipStatus: orderData.shippedCount > 0 ? 1 : 0,
          receiverName: orderData.receiverName,
          receiverPhone: orderData.receiverPhone,
          receiverAddress: orderData.receiverAddress,
          receiverRegion: orderData.receiverRegion,
          remark: orderData.remark || orderData.userNote,
          sellerRemark: orderData.sellerRemark || orderData.orderNote,
          refundStatus: afterSaleStatusNumber,
          channel: orderData.channel || orderData.liveStream,
          items: (orderData.items || []).map((item: any) => {
            // 處理商品價格
            let itemPrice = 0;
            if (typeof item.price === 'number') {
              itemPrice = item.price;
            } else if (typeof item.price === 'string') {
              itemPrice = parseFloat(item.price.replace(/[^\d.]/g, ''));
            }
            
            return {
              productName: item.productName || item.name,
              productImg: item.productImg || item.image || '/public/OIP-C.webp',
              price: itemPrice,
              quantity: item.quantity || 1,
              skuId: item.skuId || Math.floor(1000000000 + Math.random() * 9000000000).toString(),
              specifications: item.specifications || item.specs || '默认规格'
            };
          }),
          createdAt: orderData.createdAt || orderTimeDate,
          updatedAt: orderData.updatedAt || orderTimeDate
        };
        
        // 如果有客戶信息，添加到訂單數據中
        if (orderData.customerName) {
          leanCloudOrderData.customerName = orderData.customerName;
        }
        
        if (orderData.phone) {
          leanCloudOrderData.phone = orderData.phone;
        }
        
        // 如果有 totalCount 和 shippedCount，添加到訂單數據中
        if (orderData.totalCount) {
          leanCloudOrderData.totalCount = orderData.totalCount;
        }
        
        if (orderData.shippedCount !== undefined) {
          leanCloudOrderData.shippedCount = orderData.shippedCount;
        }
        
        // 如果提供了 objectId，使用 PUT 方法更新訂單，否則使用 POST 方法創建訂單
        if (objectId) {
          return {
            method: 'PUT',
            path: `/1.1/classes/Order/${objectId}`,
            body: leanCloudOrderData
          };
        } else {
          return {
            method: 'POST',
            path: `/1.1/classes/Order`,
            body: leanCloudOrderData
          };
        }
      })
    }
  });
}

/**
 * 初始化訂單數據到LeanCloud
 * 直接向LeanCloud添加示例訂單數據
 */
export function initOrderData() {
  // 使用当前时间作为基准，避免无效日期
  const now = new Date();
  const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);
  const twoDaysAgo = new Date(now.getTime() - 2 * 24 * 60 * 60 * 1000);
  const threeDaysAgo = new Date(now.getTime() - 3 * 24 * 60 * 60 * 1000);
  const fourDaysAgo = new Date(now.getTime() - 4 * 24 * 60 * 60 * 1000);
  const fiveDaysAgo = new Date(now.getTime() - 5 * 24 * 60 * 60 * 1000);

  return request({
    url: `${API.BATCH}`,
    method: 'post',
    data: {
      requests: [
        {
          method: 'POST',
          path: '/1.1/classes/Order',
          body: {
            orderNo: 'P2023090100001',
            totalAmount: 56.90,
            payAmount: 56.90,
            discountAmount: 0,
            status: 6, // 交易關閉
            payStatus: 1, // 已付款
            payType: 1, // 假設是微信支付
            payTime: { "__type": "Date", "iso": fiveDaysAgo.toISOString() },
            shipStatus: 0,
            receiverName: '周杰伦',
            receiverPhone: '13800138000',
            receiverAddress: '天朝北路1号楼',
            receiverRegion: '北京市/北京市/朝阳区/建外街道',
            remark: '',
            sellerRemark: '',
            refundStatus: 0, // 無售後
            channel: '抖音直播',
            items: [
              {
                productName: '飘柔洗护香波',
                productImg: '/public/OIP-C.webp',
                price: 56.90,
                quantity: 1,
                skuId: '2468896545',
                specifications: '默认规格'
              }
            ]
          }
        },
        {
          method: 'POST',
          path: '/1.1/classes/Order',
          body: {
            orderNo: 'P2023090100002',
            totalAmount: 128.50,
            payAmount: 128.50,
            discountAmount: 10,
            status: 2, // 待發貨
            payStatus: 1, // 已付款
            payType: 1,
            payTime: { "__type": "Date", "iso": fourDaysAgo.toISOString() },
            shipStatus: 0,
            receiverName: '林俊杰',
            receiverPhone: '13900139000',
            receiverAddress: '演唱会路2号',
            receiverRegion: '上海市/上海市/徐汇区/湖南路街道',
            remark: '请确保新鲜',
            sellerRemark: '',
            refundStatus: 0,
            channel: '官网',
            items: [
              {
                productName: '有机蔬菜礼盒',
                productImg: '/public/OIP-C.webp',
                price: 128.50,
                quantity: 1,
                skuId: '2468896546',
                specifications: '精品装'
              }
            ]
          }
        },
        {
          method: 'POST',
          path: '/1.1/classes/Order',
          body: {
            orderNo: 'P2023090100003',
            totalAmount: 269.70,
            payAmount: 269.70,
            discountAmount: 0,
            status: 3, // 部分發貨
            payStatus: 1,
            payType: 1,
            payTime: { "__type": "Date", "iso": threeDaysAgo.toISOString() },
            shipStatus: 1, // 已發貨
            shipTime: { "__type": "Date", "iso": twoDaysAgo.toISOString() },
            receiverName: '周杰伦',
            receiverPhone: '13800138000',
            receiverAddress: '天朝北路1号楼',
            receiverRegion: '北京市/北京市/朝阳区/建外街道',
            remark: '用户需要锅碗炉盘',
            sellerRemark: '',
            refundStatus: 0,
            channel: '微信小店',
            items: [
              {
                productName: '格兰仕烤箱12L 自动',
                productImg: '/public/OIP-C.webp',
                price: 69.90,
                quantity: 2,
                skuId: '2468896545',
                specifications: '默认规格'
              },
              {
                productName: '索迪斯手持除螨仪',
                productImg: '/public/OIP-C.webp',
                price: 129.90,
                quantity: 1,
                skuId: '2468896617',
                specifications: '默认规格'
              }
            ],
            shippedCount: 1,
            totalCount: 2
          }
        },
        {
          method: 'POST',
          path: '/1.1/classes/Order',
          body: {
            orderNo: 'P2023090100004',
            totalAmount: 23.80,
            payAmount: 23.80,
            discountAmount: 0,
            status: 4, // 待收貨
            payStatus: 1,
            payType: 1,
            payTime: { "__type": "Date", "iso": threeDaysAgo.toISOString() },
            shipStatus: 1,
            shipTime: { "__type": "Date", "iso": yesterday.toISOString() },
            receiverName: '周杰伦',
            receiverPhone: '13800138000',
            receiverAddress: '天朝北路1号楼',
            receiverRegion: '北京市/北京市/朝阳区/建外街道',
            remark: '',
            sellerRemark: '',
            refundStatus: 0,
            channel: '小红书订单',
            items: [
              {
                productName: '三十九度超鲜 国产贵妃芒',
                productImg: '/public/OIP-C.webp',
                price: 23.80,
                quantity: 1,
                skuId: '2468896545',
                specifications: '默认规格'
              }
            ],
            shippedCount: 1,
            totalCount: 1
          }
        },
        {
          method: 'POST',
          path: '/1.1/classes/Order',
          body: {
            orderNo: 'P2023090100005',
            totalAmount: 56.90,
            payAmount: 56.90,
            discountAmount: 0,
            status: 5, // 交易完成
            payStatus: 1,
            payType: 1,
            payTime: { "__type": "Date", "iso": fiveDaysAgo.toISOString() },
            shipStatus: 1,
            shipTime: { "__type": "Date", "iso": fourDaysAgo.toISOString() },
            receiveTime: { "__type": "Date", "iso": twoDaysAgo.toISOString() },
            receiverName: '周杰伦',
            receiverPhone: '13800138000',
            receiverAddress: '天朝北路1号楼',
            receiverRegion: '北京市/北京市/朝阳区/建外街道',
            remark: '',
            sellerRemark: '',
            refundStatus: 0,
            channel: '蝉蜕号',
            items: [
              {
                productName: '正大食品（CP）鸡翅中',
                productImg: '/public/OIP-C.webp',
                price: 56.90,
                quantity: 1,
                skuId: '2468896545',
                specifications: '默认规格'
              }
            ],
            shippedCount: 1,
            totalCount: 1
          }
        },
        {
          method: 'POST',
          path: '/1.1/classes/Order',
          body: {
            orderNo: 'P2023090100006',
            totalAmount: 56.90,
            payAmount: 56.90,
            discountAmount: 0,
            status: 6, // 交易關閉
            payStatus: 1,
            payType: 1,
            payTime: { "__type": "Date", "iso": twoDaysAgo.toISOString() },
            shipStatus: 0,
            receiverName: '周杰伦',
            receiverPhone: '13800138000',
            receiverAddress: '天朝北路1号楼',
            receiverRegion: '北京市/北京市/朝阳区/建外街道',
            remark: '',
            sellerRemark: '',
            refundStatus: 0,
            channel: '抖音直播',
            items: [
              {
                productName: '飘柔洗护香波',
                productImg: '/public/OIP-C.webp',
                price: 56.90,
                quantity: 1,
                skuId: '2468896545',
                specifications: '默认规格'
              }
            ]
          }
        }
      ]
    }
  });
} 